package pay

import (
	"errors"
	"github.com/smartwalle/alipay/v3"
	"go-admin-official/modules/config"
	"go-admin-official/modules/logger"
	"go-admin-official/modules/utils"
	"strconv"
	"sync"
	"time"
)

var aliClient = new(alipay.Client)

func InitAliPay() {
	var err error
	aliClient, err = alipay.New(config.Get().AliPayAppID, config.Get().AliPayPrivateKey, true)
	if err != nil {
		logger.Error("alipay init error: ", err)
		return
	}
	err = aliClient.LoadAliPayPublicKey(config.Get().AliPayPublicKey)
	if err != nil {
		logger.Error("alipay init error: ", err)
		return
	}
	logger.Info("init alipay...")
}

const aliNotifyURL = "http://goadmin.ng.dadadaa.com/api/pay/callback/alipay"

//const aliNotifyURL = "https://www.go-admin.com/api/pay/callback/alipay"

func GetWebAliPayConfig(no, title, amount string) (string, error) {
	res, err := aliClient.TradePreCreate(alipay.TradePreCreate{
		Trade: alipay.Trade{
			NotifyURL:   aliNotifyURL,
			Subject:     title,  // 订单标题
			OutTradeNo:  no,     // 商户订单号，64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
			TotalAmount: amount, // 订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
		},
	})
	if err != nil {
		logger.Error("GetWebAliPayConfig error: ", err, "order", no)
		return "", err
	}
	if !res.IsSuccess() {
		logger.Error("GetWebAliPayConfig response error: ", res.Content, "order", no)
		return "", errors.New(res.Content.Msg)
	}
	return res.Content.QRCode, nil
}

var orderGenerateLock sync.Mutex

func GenerateOrderNum() string {
	orderGenerateLock.Lock()
	defer orderGenerateLock.Unlock()

	return time.Now().Format("20060102") + utils.Uuid(5) + strconv.FormatInt(time.Now().UnixNano(), 10)
}
